package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Resource
    private DishService dishService;

    @Resource
    private DishFlavorService dishFlavorService;

    @Resource
    private CategoryService categoryService;
    /**
     * 菜品分页
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @Transactional
    @GetMapping("/page")
    public R<Page> page( int page, int pageSize, String name) {
        log.info("page = {},pageSize = {},name = {}",page,pageSize,name);
        Page<Dish> pageInfo = new Page<Dish>(page,pageSize);
        Page<DishDto> dishDtoPage=new Page<DishDto>();
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper=new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(Dish::getIsDeleted,0);
        dishLambdaQueryWrapper.like(StringUtils.isNotEmpty(name),Dish::getName,name);
        dishLambdaQueryWrapper.orderByDesc(Dish::getSort);
        //执行分页查询
        dishService.page(pageInfo,dishLambdaQueryWrapper);
        //对象拷贝
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list=records.stream().map((item) ->{
            DishDto dishDto=new DishDto();
            //拷贝其他数据
            BeanUtils.copyProperties(item,dishDto);

            //拿到分类id
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if(category!=null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }

    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
    log.info(dishDto.toString());
    dishService.saveWithFlavor(dishDto);
    return R.success("新增菜品成功!");
    }

    /**
     * 根据id查询菜品信息和对应的口味信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> update(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> set(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);
        return R.success("修改菜品成功!");
    }
    @Transactional
    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable("status") int status,@RequestParam String ids){
        log.info(ids);
        log.info(String.valueOf(status));
        List<Dish> dishList=new ArrayList<>();
        for (String s : ids.split(",")) {
            Dish dish=new Dish();
            dish.setId(Long.parseLong(s));
            dish.setStatus(status);
            dishList.add(dish);
        }
        dishService.updateBatchById(dishList);
        return R.success("修改状态成功!");
    }
    @Transactional
    @DeleteMapping()
    public R<String> delete(@RequestParam String ids){
        log.info(ids);
        List<DishDto> dishDtoList=new ArrayList<>();
        List<Long> dishIds = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());
        for (String s : ids.split(",")) {
            DishDto dishDto=new DishDto();
            dishDto.setId(Long.parseLong(s));
            dishDto.setIsDeleted(1);
            dishDtoList.add(dishDto);
        }
        //删除菜品数据
        List<Dish> dishList=dishDtoList.stream().map((item)->{
            Dish dish=new Dish();
            BeanUtils.copyProperties(item,dish);
            return dish;
        }).collect(Collectors.toList());
        dishService.updateBatchById(dishList);
        log.info("删除菜品数据成功!!!");
        //删除口味数据
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper=new LambdaQueryWrapper<DishFlavor>();
        dishFlavorLambdaQueryWrapper.in(DishFlavor::getDishId,dishIds);
        List<DishFlavor> flavors = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
        flavors=flavors.stream().map((item)->{
            DishFlavor dishFlavor=new DishFlavor();
            item.setIsDeleted(1);
            BeanUtils.copyProperties(item,dishFlavor);
            return dishFlavor;
        }).collect(Collectors.toList());
        dishFlavorService.updateBatchById(flavors);
        log.info("删除口味数据成功!!!");
        return R.success("删除成功!");
    }

/*    @GetMapping("/list")
    public R<List<Dish>> list(Dish dish){
        LambdaQueryWrapper<Dish> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(dish.getCategoryId() !=null,Dish::getCategoryId,dish.getCategoryId());
        wrapper.eq(Dish::getStatus,1);
        wrapper.orderByDesc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(wrapper);
        return R.success(list);
    }*/

    /**
     * 菜品和口味数据
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        LambdaQueryWrapper<Dish> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(dish.getCategoryId() !=null,Dish::getCategoryId,dish.getCategoryId());
        wrapper.eq(Dish::getStatus,1);
        wrapper.orderByDesc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(wrapper);

        List<DishDto> dishDtoList=list.stream().map((item) ->{
            DishDto dishDto=new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId();
            //查询分类对象数据
            Category category = categoryService.getById(categoryId);
            if(category!=null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            //菜品id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> wrapper1=new LambdaQueryWrapper<>();
            wrapper1.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> dishFlavors = dishFlavorService.list(wrapper1);
            dishDto.setFlavors(dishFlavors);

            return dishDto;

        }).collect(Collectors.toList());
        return R.success(dishDtoList);
    }


}
